﻿//==============================================================================
// File: WorkbenchService.cs
// Created: 2010-05-28
// Author: Piotr Włodek, Arkadiusz Świerczek
//==============================================================================
// This file is a part of MAMMOTH project.
// Copyright (C) 2010 AGH University of Science and Technology, Krakow.
// https://caribou.iisg.agh.edu.pl/trac/mammoth
//
// Mammoth is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// Mammoth is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public License
// along with Mammoth. If not, see http://www.gnu.org/licenses/.
//==============================================================================

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using WpfRcp.Controls;
using WpfRcp.Controls.Behaviors;
using WpfRcp.Core.Common;
using WpfRcp.Core.Common.Workbench;
using WpfRcp.Core.Globals;
using WpfRcp.Core.Services;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.Unity;
using WpfRcp.Core.Views;

namespace WpfRcp.Services
{
    public class WorkbenchService : BindableBase, IWorkbenchService
    {
        #region Attached Properties

        private static WorkbenchItem GetWorkbenchItem(DependencyObject obj)
        {
            return (WorkbenchItem)obj.GetValue(WorkbenchItemProperty);
        }

        private static void SetWorkbenchItem(DependencyObject obj, WorkbenchItem value)
        {
            obj.SetValue(WorkbenchItemProperty, value);
        }

        private static readonly DependencyProperty WorkbenchItemProperty =
            DependencyProperty.RegisterAttached("WorkbenchItem", typeof(WorkbenchItem), typeof(WorkbenchService),
                                                new UIPropertyMetadata(null));

        #endregion

        // Instance fields
        private readonly IRegionManager m_RegionManager;
        private readonly RegionBasedTabMenuDockManager m_DockManager;
        private readonly IEventAggregator m_EventAggregator;
        private readonly ILoggerService m_LoggerService;
        private readonly ObservableCollection<WorkbenchItem> m_WorkbenchItems = new ObservableCollection<WorkbenchItem>();
        private readonly ReadOnlyObservableCollection<WorkbenchItem> m_ReadOnlyWorkbenchItems;
        private bool m_IsRegionAttached;
        private IShell m_Shell;

        public WorkbenchService(
            IRegionManager regionManager,
            IEventAggregator eventAggregator,
            ILoggerService loggerService,
            RegionBasedTabMenuDockManager dockManager,
            IShell shell)
        {
            m_RegionManager = regionManager;
            m_EventAggregator = eventAggregator;
            m_LoggerService = loggerService;
            m_DockManager = dockManager;
            m_ReadOnlyWorkbenchItems = new ReadOnlyObservableCollection<WorkbenchItem>(m_WorkbenchItems);

            m_DockManager.ContentClosed += (sender, e) =>
            {
                if (e.Content != null)
                {
                    WorkbenchItem workbenchItem = GetWorkbenchItem(e.Content);
                    Remove((ViewItem)workbenchItem);
                }
            };

            m_Shell = shell;
        }

        #region IWorkbenchService Members

        public IList<WorkbenchItem> WorkbenchItems
        {
            get { return m_ReadOnlyWorkbenchItems; }
        }

        public DocumentItem ActiveDocument
        {
            get
            {
                if (ActiveView != null)
                {
                    return (DocumentItem)ActiveView.Tag;
                }
                return null;
            }
        }

        public void Add(DocumentItem workbenchItem)
        {
            if (!m_IsRegionAttached)
            {
                m_RegionManager.Regions[RegionNames.DocumentRegion].ActiveViews.CollectionChanged += ActiveViews_CollectionChanged;
                m_RegionManager.Regions[RegionNames.DocumentRegion].Views.CollectionChanged += Views_CollectionChanged;
                m_IsRegionAttached = true;
            }

            DateTime start = DateTime.Now;

            var tabItem = m_Shell.GetTabMenuItemInstance(RegionNames.DocumentRegion);

            m_DockManager.RegisterItem(tabItem, RegionNames.DocumentRegion);

            tabItem.Tag = workbenchItem;
            tabItem.Content = workbenchItem.Visual;

            var binding = new Binding("Name") { Source = workbenchItem };

            BindingOperations.SetBinding(tabItem as DependencyObject, tabItem.HeaderTitleProperty, binding);

            m_RegionManager.Regions[RegionNames.DocumentRegion].Add(tabItem);

            if(ActiveView != null)
                m_RegionManager.Regions[RegionNames.DocumentRegion].Deactivate(ActiveView);
            m_RegionManager.Regions[RegionNames.DocumentRegion].Activate(tabItem);

            tabItem.UpdateLayout();

            DateTime end = DateTime.Now;

            // Log that the document has been opened
            m_LoggerService.Log(string.Format(Properties.Resources.DocumentOpened, workbenchItem.Name, (end - start).TotalMilliseconds),
                         "WpfRcp.UI", TraceEventType.Information, Properties.Resources.Vizualization);
        }

        public void Add(ViewItem viewItem)
        {
            Add(viewItem, DockStyle.RightPanel);
        }

        public void Add(ViewItem viewItem, DockStyle style)
        {
            if (viewItem.Visual is TabMenuItemWindow)
            {
                var window = (TabMenuItemWindow) viewItem.Visual;
                var content = (DependencyObject) window.Content;

                if (content == null || GetWorkbenchItem(content) != null)
                    return;
                
                var menuItem = new TabMenuItem
                {
                    IsDetachable = true,
                    Header = window.Title,
                    IsCloseable = window.IsCloseButtonVisible
                };

                viewItem.Visual = content;
                window.MenuItem = menuItem;
                SetWorkbenchItem(content, viewItem);

                if (WindowBehavior.GetHideInsteadClose(window))
                {
                    m_DockManager.RegisterSingletonWindow(window, RegionNames.BottomRegion);
                }
                else
                {
                    m_DockManager.RegisterWindow(window);
                }

                m_DockManager.RegisterItem(menuItem, RegionNames.BottomRegion);
                window.Show();
            }
            else
            {
                var item = GetWorkbenchItem((DependencyObject) viewItem.Visual);
                if (item != null)
                    return;

                SetWorkbenchItem((DependencyObject) viewItem.Visual, viewItem);

                var tabMenuItem = m_Shell.GetTabMenuItemInstance(style == DockStyle.BottomPanel ? RegionNames.BottomRegion : RegionNames.SidePanelRegion);

                tabMenuItem.Content = viewItem.Visual;

                var binding = new Binding("Name") { Source = viewItem };
                BindingOperations.SetBinding(tabMenuItem as DependencyObject, tabMenuItem.HeaderTitleProperty, binding);

                if (style == DockStyle.BottomPanel)
                {
                    m_RegionManager.Regions[RegionNames.BottomRegion].Add(tabMenuItem);
                }
                else
                {
                    m_RegionManager.Regions[RegionNames.SidePanelRegion].Add(tabMenuItem);
                }

                m_DockManager.RegisterItem(tabMenuItem, RegionNames.SidePanelRegion);
            }

            m_WorkbenchItems.Add(viewItem);

        }

        public void AddGroup(DockStyle style, ViewItem viewItem, params ViewItem[] viewItems)
        {
            Add(viewItem, style);
            foreach (var item in viewItems)
            {
                if (item != null)
                    Add(item, style);
            }
        }

        public void Remove(DocumentItem workbenchItem)
        {
            ITabMenuItem item2Remove = null;
            foreach (ITabMenuItem tabItem in m_RegionManager.Regions[RegionNames.DocumentRegion].Views)
            {
                if(tabItem.Tag == workbenchItem)
                {
                    item2Remove = tabItem;
                    break;
                }
            }

            m_RegionManager.Regions[RegionNames.DocumentRegion].Remove(item2Remove);
        }

        public void Remove(ViewItem viewItem)
        {
            if (viewItem != null)
            {
                m_WorkbenchItems.Remove(viewItem);
                SetWorkbenchItem((DependencyObject) viewItem.Visual, null);
            }
        }

        public void RemoveDocuments()
        {
            var viewsCopy = new List<object>(m_RegionManager.Regions[RegionNames.DocumentRegion].Views);
            
            foreach (ITabMenuItem item in viewsCopy)
            {
                m_RegionManager.Regions[RegionNames.DocumentRegion].Remove(item);
            }
        }

        #endregion

        private ITabMenuItem ActiveView
        {
            get
            {
                if (m_RegionManager.Regions[RegionNames.DocumentRegion].ActiveViews.Any())
                {
                    return (ITabMenuItem)m_RegionManager.Regions[RegionNames.DocumentRegion].ActiveViews.First();
                }
                return null;
            }
        }

        private void ActiveViews_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            var someEvent = m_EventAggregator.GetEvent<ActiveWorkbenchItemChangedEvent>();
            someEvent.Publish(ActiveDocument);

            OnPropertyChanged("ActiveDocument");
        }

        private void Views_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.OldItems != null)
            {
                foreach (ITabMenuItem tabItem in e.OldItems)
                {
                    m_WorkbenchItems.Remove((WorkbenchItem) tabItem.Tag);
                }
            }

            if (e.NewItems != null)
            {
                foreach (ITabMenuItem tabItem in e.NewItems)
                {
                    m_WorkbenchItems.Add((WorkbenchItem)tabItem.Tag);
                }
            }
        }

    }
}